//mysql连接池配置文件
const mysql = require("mysql");
const $dbConfig = require("./dbConfig.js"); //注意改成自己项目中mysql配置文件的路径
const sql = require("./sql.js"); //
const mysqlDB = mysql.createPool($dbConfig.base); // 使用连接池，避免开太多的线程，提升性能
const execs = require('child_process').exec
const json = require("./json.js");
const exe = require('./exe.js');
const common = require("./common.js");
const {  setOperationLog } = require("../middleware/recordLog.js");
/**
 * @description 新增一条数据
 * @param  {str} table 数据库表的名称
 * @param  {obj} req 插入的数据
 * @param  {obj} res 接口函数中的res对象
 * @param  {obj} next 接口函数中的next对象
 */
const isRunning = (query, cb) => {
  let platform = process.platform
  let cmd = ''
  switch (platform) {
    case 'win32':
      cmd = `tasklist`
      break
    case 'darwin':
      cmd = `ps -ax | grep ${query}`
      break
    case 'linux':
      cmd = `ps -A`
      break
    default:
      break
  }
  execs(cmd, (err, stdout, stderr) => {
    cb(stdout.toLowerCase().indexOf(query.toLowerCase()) > -1)
  })
}
//查询最近一天各电柜耗能   ------------------------------------
let GetElectricAct = (table, params, res) => {
  const { date } = params;
  var pool = mysqlDB;
  let date1 = ` '${date}' `
  if (!date) {
    date1 = " (select max(date) from electric_history ) ";
  }
  let sqlString = `SELECT eh.e_id,bb.equipment as name, eh.value, sum(eh.diff) as diff, eh.createTime FROM electric_history eh INNER JOIN (    SELECT e_id, MAX(createTime) AS latestTime    FROM electric_history    WHERE DATE(createTime) = ${date1}    GROUP BY e_id) latest_records ON eh.e_id = latest_records.e_id AND eh.createTime = latest_records.latestTime left join config bb on eh.e_id = bb.e_id WHERE DATE(eh.createTime) = ${date1} group by equipment  order by diff desc;`;
  pool.getConnection((err, connection) => {
    if (!err) {
      connection.query(sqlString, (err, result) => {
        if (err) {
          console.log(err);
          res.json({
            code: "300",
            msg: "操作失败:",
          });
        } else {
          if (result != "") {
            var _result = result;
            result = {
              result: "selectall",
              data: _result,
            };
          } else {
            result = undefined;
          }
          global.result = result;

          json(res, result, err);
        }

        connection.release();
      });
    } else {
      console.log(err);
      ;
      json(res, "444", err);
    }
  });
};

//查询最近十天总耗能   ------------------------------------
let Get10DaySum = (table, params, res) => {
  let { startDate, endDate } = params
  startDate = startDate ? `and eh.date >='${startDate}'` : "";
  endDate = endDate ? `and eh.date <='${endDate}' ` : "";
  let sqlString = sql[table].Get10DaySum + startDate + endDate + " GROUP BY date order by date desc limit 100;";
  var pool = mysqlDB;
  pool.getConnection((err, connection) => {
    if (!err) {
      connection.query(sqlString, (err, result) => {
        if (err) {
          console.log(err);
          res.json({
            code: "300",
            msg: "操作失败:",
          });
        } else {
          if (result != "") {
            var _result = result;
            result = {
              result: "selectall",
              data: _result,
            };
          } else {
            result = undefined;
          }
          global.result = result;

          json(res, result, err);
        }

        connection.release();
      });
    } else {
      console.log(err);
      ;
      json(res, "444", err);
    }
  });
};
//查询每小时总耗能   ------------------------------------
let GetHourSum = (table, params, res) => {
  let { date, name } = params;
  let where = `where date = '${date}' and name like '%${name}%' group by hour order by createTime`;
  if (date == '') {
    where =
      `where date = (select max(date) from electric_history_hour ) and name like '%${name}%' group by hour order by createTime `;
  }
  var pool = mysqlDB;
  let sqlString =
    sql[table].GetHourSum + where
  pool.getConnection((err, connection) => {
    if (!err) {
      connection.query(sqlString, [date], (err, result) => {
        if (err) {
          console.log(err);
          res.json({
            code: "300",
            msg: "操作失败:",
          });
        } else {
          if (result != "") {
            var _result = result;
            result = {
              result: "selectall",
              data: _result,
            };
          } else {
            result = undefined;
          }
          global.result = result;

          json(res, result, err);
        }

        connection.release();
      });
    } else {
      console.log(err);
      ;
      json(res, "444", err);
    }
  });
};
//查询最近月份总耗能   ------------------------------------
let GetMonthSum = (table, params, res) => {
  const { years } = params
  var pool = mysqlDB;
  pool.getConnection((err, connection) => {
    if (!err) {
      connection.query(sql[table].GetMonthSum, [years], (err, result) => {
        if (err) {
          console.log(err);
          res.json({
            code: "300",
            msg: "操作失败:",
          });
        } else {
          if (result != "") {
            var _result = result;
            result = {
              result: "selectall",
              data: _result,
            };
          } else {
            result = undefined;
          }
          global.result = result;

          json(res, result, err);
        }

        connection.release();
      });
    } else {
      console.log(err);
      ;
      json(res, "444", err);
    }
  });
};
//查询配置参数  ------------------------------------
let GetConfigPara = (table, res) => {
  var pool = mysqlDB;
  pool.getConnection((err, connection) => {
    if (!err) {
      connection.query(sql[table].GetConfigPara, (err, result) => {
        if (err) {
          console.log(err);
          res.json({
            code: "300",
            msg: "操作失败:",
          });
        } else {
          if (result != "") {
            var _result = result;
            result = {
              result: "selectall",
              data: _result,
            };
          } else {
            result = undefined;
          }
          global.result = result;

          json(res, result, err);
        }

        connection.release();
      });
    } else {
      console.log(err);
      ;
      json(res, "444", err);
    }
  });
};
//条件查询历史电能   ------------------------------------
let GetHistorySearch = (table, params, res) => {
  const { name, startDate, endDate } = params;
  let startDate1 = startDate ? ` AND createTime >= '${startDate}' ` : "";
  let endDate1 = endDate
    ? ` AND createTime <=  '${endDate}' `
    : " AND createTime <= (select max(createTime) from electric_history ) ";
  let sqlString = `select * from electric_history WHERE name = '${name}' ${startDate1} ${endDate1} order by createTime desc limit 30`;
  var pool = mysqlDB;
  pool.getConnection((err, connection) => {
    if (!err) {
      connection.query(sqlString, (err, result) => {
        if (err) {
          console.log(err);
          res.json({
            code: "300",
            msg: "操作失败:",
          });
        } else {
          if (result != "") {
            var _result = result;
            result = {
              result: "selectall",
              data: _result,
            };
          } else {
            result = undefined;
          }
          global.result = result;

          json(res, result, err);
        }

        connection.release();
      });
    } else {
      console.log(err);
      ;
      json(res, "444", err);
    }
  });
};
// 编辑配置信息
let EditData = (table, req, res) => {
  const { data } = req.body;
  delete data.updateTime;
  delete data.is_delete;
  formData = [Object.values(data)];
  var pool = mysqlDB;
  pool.getConnection((err, connection) => {
    if (!err) {
      connection.query(sql[table].EditData, [formData], (err, result) => {
        if (err) {
          console.log(err);
          // 更新操作日志
          setOperationLog(req, undefined);
          res.json({
            code: "300",
            msg: "操作失败:",
          });
        } else {
          if (result != "") {
            result = "update";
          } else {
            result = undefined;
          }
          global.result = result;
          // 更新操作日志
          setOperationLog(req, result);
          json(res, result, err);
        }

        connection.release();
      });
    } else {
      console.log(err);
      ;
      json(res, "444", err);
    }
  });
};
// 新增配置信息
let AddData = (table, req, res) => {
  const { data } = req.body;
  let date = common.getNowTime();
  formData = [
    [
      data.ip,
      data.equipment,
      data.name,
      data.position,
      data.area,
      data.number,
      data.byte,
      data.length,
      data.enable ? data.enable : 0,
      date,
    ],
  ];
  var pool = mysqlDB;
  pool.getConnection((err, connection) => {
    if (!err) {
      connection.query(sql[table].AddData, [formData], (err, result) => {
        if (err) {
          console.log(err);
          // 更新操作日志
          setOperationLog(req, undefined);
          res.json({
            code: "300",
            msg: "操作失败:",
          });
        } else {
          if (result != "") {
            result = "add";
          } else {
            result = undefined;
          }
          global.result = result;
          // 更新操作日志
          setOperationLog(req, result);
          json(res, result, err);
        }

        connection.release();
      });
    } else {
      console.log(err);
      ;
      json(res, "444", err);
    }
  });
};
// 删除一条配置
let DeleteData = (table, req, res) => {
  const { e_id } = req.body;
  var pool = mysqlDB;
  pool.getConnection((err, connection) => {
    if (!err) {
      connection.query(sql[table].DeleteData, [e_id], (err, result) => {
        if (err) {
          console.log(err);
          // 更新操作日志
          setOperationLog(req, undefined);
          res.json({
            code: "300",
            msg: "操作失败:",
          });
        } else {
          if (result != "") {
            result = "delete";
          } else {
            result = undefined;
          }
          global.result = result;
          // 更新操作日志
          setOperationLog(req, result);
          json(res, result, err);
        }

        connection.release();
      });
    } else {
      console.log(err);
      ;
      json(res, "444", err);
    }
  });
};
//视觉识别程序是否开启------------------------------------
let ifrunning = (appname, res) => {
  isRunning(appname, (status) => {
    if (status) {
      res.json({
        code: '200',
        msg: "程序启动成功！",
      })
    } else {
      res.json({
        code: '250',
        msg: "程序未运行",
      })
    }
  })
};
//开启视觉识别------------------------------------
let startCollect = (dir, paths, pathname, res) => {
  // var command =  `D: && cd D:\paige_main && paige_main.exe`
  var command = `${dir} && cd ${dir}\\${paths} && ${pathname}.exe`
  isRunning(pathname, (status) => {
    if (!status) {
      exe.Controlexe(command, res, (status) => { })
      return
    } else {
      command = `taskkill /f /t /im ${pathname}.exe`
      exe.Controlexe(command, res, (status) => { })
    }
  })
  res.json({
    code: '200',
    msg: "请求成功",
  })
};




/**
 * @description 遍历数据的值
 * @param {obj} obj 包含参数的对象
 * */
let paramList = (obj) => {
  let paramArr = [];
  for (let key in obj) {
    if (obj[key]) {
      paramArr.push(obj[key]);
    }
  }
  return paramArr;
};

module.exports = {
  startCollect,
  ifrunning,
  GetElectricAct,
  Get10DaySum,
  GetMonthSum,
  GetConfigPara,
  GetHistorySearch,
  GetHourSum,
  EditData,
  AddData,
  DeleteData,
};